package com.llyb.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.llyb.tingshu.album.service.TrackInfoService;
import com.llyb.tingshu.common.rabbit.constant.MqConst;
import com.llyb.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author atguigu-mqx
 * @ClassName TrackReceiver
 * @description: TODO
 * @date 2025年09月09日
 * @version: 1.0
 */
@Component
@Slf4j
public class TrackReceiver {

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = {MqConst.ROUTING_TRACK_STAT_UPDATE}
    ))
    public void updateTrackStat(String msg, Message message, Channel channel){
        try {
            //  先判断当前数据：
            if (!StringUtils.isEmpty(msg)){
                //  数据类型专辑：
                TrackStatMqVo trackStatMqVo = JSON.parseObject(msg, TrackStatMqVo.class);
                //  获取交易编号; 防止消息重复消费;
                String businessNo = trackStatMqVo.getBusinessNo();
                //  执行成功；说明是第一次消费：
                Boolean result = this.redisTemplate.opsForValue().setIfAbsent(businessNo, "1", 10, TimeUnit.MINUTES);
                if (result){
                    try {
                        //  调用服务层方法：
                        trackInfoService.updateStat(trackStatMqVo);
                    } catch (Exception e) {
                        //  异常中，删除上一个key;
                        this.redisTemplate.delete(businessNo);
                        log.error(e.getMessage(),e);
                    }
                }

            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }

        //  手动确认;
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
